package com.xuantian.baoming.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuantian.baoming.BaomingApplication;
import com.xuantian.baoming.entity.OrderInfo;
import com.xuantian.baoming.entity.WorksInfo;
import com.xuantian.baoming.enums.OrderStatus;
import com.xuantian.baoming.service.OrderInfoService;
import com.xuantian.baoming.service.WorksInfoService;
import com.xuantian.baoming.util.CurrentDateTime;
import com.xuantian.baoming.util.UserAgentUtil;
import com.xuantian.baoming.vo.R;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@CrossOrigin //开放前端的跨域访问
@RestController
@RequestMapping("/works")
@Slf4j
public class WorksInfoController {
    @Autowired
    private WorksInfoService worksInfoService;
    @Autowired
    private OrderInfoService orderInfoService;

    /**
     * 作品上传
     * @param worksInfo
     */
    @PostMapping("/save")
    private R save(@RequestBody WorksInfo worksInfo) {

        //用户是否缴费报名。报名后才可以上传作品

        OrderInfo orderInfo = orderInfoService.selectOrderByContact(worksInfo.getContact(), worksInfo.getName());
        String successType = OrderStatus.SUCCESS.getType();
        if(orderInfo == null || !orderInfo.getStatus().equals(successType)){
            return R.fail(500,"请先报名，再上传作品!");
        }

        //先查询是否已存在，存在更新，不存在新增
        WorksInfo worksInfo1 = worksInfoService.queryNameAndContact(worksInfo);
        if(worksInfo1 != null){
            worksInfo.setId(worksInfo1.getId());
            worksInfo.setCreateTime(new Date());
        }
        worksInfoService.saveOrUpdate(worksInfo);

        return R.ok();
    }

    /**
     * 分页条件查询订单
     * @param page
     * @param size
     * @param name
     * @param contact
     * @return
     */
    @GetMapping("/list")
    public R<IPage<WorksInfo>> list(@RequestParam(required = false) Integer page,
                                    @RequestParam(required = false) Integer size,
                                    @RequestParam(required = false) String name,
                                    @RequestParam(required = false) String contact,
                                    @RequestParam(required = false) String grade
                                    ) {
        // 设置默认分页参数
        if (page == null || size == null) {
            page = 1;
            size = 10;
        }
        // 创建分页对象
        Page<WorksInfo> pageInfo = new Page<>(page, size);
        // 创建条件构造器
        LambdaQueryWrapper<WorksInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(!StringUtils.isEmpty(name), WorksInfo::getName, name);
        wrapper.like(!StringUtils.isEmpty(grade), WorksInfo::getGrade, grade);
        wrapper.like(!StringUtils.isEmpty(contact), WorksInfo::getContact, contact);
        // 执行分页查询
        IPage<WorksInfo> result = worksInfoService.page(pageInfo, wrapper);
        // 返回结果
        return R.ok(result);
    }

    /**
     * 根据id查询时，修改状态，0未读，1已读
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R queryOrderInfoById(@PathVariable Long id) {

        WorksInfo worksInfo = worksInfoService.getById(id);
        if (worksInfo == null){
            return R.fail("订单不存在");
        }
        if (worksInfo.getStatus() == 1){
            return R.ok(worksInfo);
        }
        worksInfo.setStatus(1);
        worksInfoService.updateById(worksInfo);
        //修改查询状态
        return R.ok(worksInfo);
    }
    @GetMapping ("/excelWorksInfo")
    @SneakyThrows
    private void excelExprot(HttpServletResponse response,@RequestParam("ids") Integer[] ids ){

        List<WorksInfo> worksInfos = worksInfoService.listByIds(Arrays.asList(ids));


        String grade = null;

        // 根据 id 列表查询作品信息
        for (WorksInfo worksInfo : worksInfos){
            String workParticulars = worksInfo.getWorkParticulars();
            String s = removeH5Label(workParticulars);
            grade = worksInfo.getGrade();
            worksInfo.setWorkParticulars(s);
        }
        //new SimpleDateFormat("yyyyMMdd").format(new Date())

        String fileName0 = URLEncoder.encode("首届浙江省校园诗歌大赛" + grade + "作品信息汇总表", "UTF-8");

        String fileName =fileName0 + System.currentTimeMillis();

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename= " + fileName + ".xlsx");

        try (ServletOutputStream outputStream = response.getOutputStream();
             InputStream excelTemplate = BaomingApplication.class.getClassLoader().getResourceAsStream("首届浙江省诗歌大赛.xlsx")
        ) {

            // 使用 EasyExcel 写入
            EasyExcel.write(outputStream)
                    .withTemplate(excelTemplate)
                    .sheet()
                    .doFill(worksInfos);

            // 刷新输出流
            outputStream.flush();

        } catch (IOException e) {
            // 记录异常日志，并在必要时返回错误响应
            log.error("Error generating Excel file: ", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }

        log.info("========》 excel导出成功,文件名称: {}", fileName);
    }
    public String removeH5Label(String h5String){

        if (h5String.startsWith("\"") && h5String.endsWith("\"")) {
            h5String = h5String.substring(1, h5String.length() - 1);
        }

        // 替换 <p> 标签为换行符，并去除其他 HTML 标签
        String workParticulars = h5String.replaceAll("<p>", "\n").replaceAll("</p>", "")
                .replaceAll("<[^>]+>", ""); // 去掉其他标签

        return workParticulars;
    }

}
